package de.koblenz.bildung.android.sockethelper;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

public class SocketBluetooth implements ISocket
{
	private String mAddress;
	private BluetoothSocket mSocket;
	private UUID mUuid;
	
	public SocketBluetooth(String address, String uuid)
	{
		mAddress = address;
		mUuid = UUID.fromString(uuid);
	}
	
	public SocketBluetooth(String address, UUID uuid)
	{
		mAddress = address;
		mUuid = uuid;
	}
	
	@Override
	public void close() throws IOException
	{
		if(mSocket == null)
			throw new IOException();
		mSocket.close();
	}
	
	@Override
	public void connect() throws IOException
	{
		BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
		BluetoothDevice device = adapter.getRemoteDevice(mAddress);
		mSocket = device.createRfcommSocketToServiceRecord(mUuid);
		mSocket.connect();
	}
	
	@Override
	public String getHostName()
	{
		return BluetoothAdapter.getDefaultAdapter().getName();
	}
	
	@Override
	public InputStream getInputStream() throws IOException
	{
		if(mSocket == null)
			throw new IOException();
		return mSocket.getInputStream();
	}

	@Override
	public OutputStream getOutputStream() throws IOException
	{
		if(mSocket == null)
			throw new IOException();
		return mSocket.getOutputStream();
	}
}
